package com.friend.joey.applicationfriend.Fragments;


import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.friend.joey.applicationfriend.Adapters.SearchAdaper;
import com.friend.joey.applicationfriend.Classes.Result;
import com.friend.joey.applicationfriend.MainActivity;
import com.friend.joey.applicationfriend.R;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;

/**
 * Created by Joey on 2017/4/20.
 */

public class FragmentFriend extends Fragment {

//    private List<FriendItem> remList = new ArrayList<>();//备忘消息
    private static final int TYPE_ONE=0;
    private static final int TYPE_ALL=1;
    private static final int TYPE_STOP=2;
    private ArrayList<Result> musicList=new ArrayList<>();
    private MainActivity mactivity;
    private SearchAdaper adapter;
    private RecyclerView remRecyclerView;
    private Toolbar toolbar;
    private MediaPlayer mediaPlayer;
    private ImageButton play;
    private ImageButton changetype;
    private TextView songtext;
    private TextView typetext;
    private int type;
    private int number;
    private boolean isnew;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_friend, container, false);
        mactivity =(MainActivity)getActivity();
        remRecyclerView = (RecyclerView)view.findViewById(R.id.friend_recycler_view);
        toolbar=(Toolbar)view.findViewById(R.id.toolbarFriend);
        play=(ImageButton)view.findViewById(R.id.button_ffplay);
        changetype=(ImageButton)view.findViewById(R.id.button_fftype);
        songtext=(TextView)view.findViewById(R.id.txt_ffsong);
        typetext=(TextView)view.findViewById(R.id.txt_fftype);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //
        setHasOptionsMenu(true);
        if (toolbar != null) {
            toolbar.setTitle("  ");
            toolbar.setNavigationIcon(R.drawable.computer3);
        }
        mactivity.setSupportActionBar(toolbar);
        type=2;
        number=0;
        isnew=true;
        if(type == TYPE_STOP){
            typetext.setText("方式：不循环");
        }
        if(type == TYPE_ONE){
            typetext.setText("方式：单曲循环");
        }
        if(type == TYPE_ALL){
            typetext.setText("方式：列表循环");
        }

        //
        initMusic();
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        remRecyclerView.setLayoutManager(layoutManager);
        adapter = new SearchAdaper(musicList,SearchAdaper.TYPE_MUSIC);
        adapter.setOnSearchCallback(new SearchAdaper.onSearchCallback() {
            @Override
            public void onDeleteclick(int itempostion) {

            }

            @Override
            public void onShowclick(int itempostion) {
                number=itempostion;
//                if(!musicplay(musicList.get(itempostion).getURL())){
//                    Toast.makeText(mactivity, "播放失败", Toast.LENGTH_SHORT).show();
//                }
                musicplay();
            }
        });
        remRecyclerView.setAdapter(adapter);
        mediaPlayer=new MediaPlayer();
        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                if(type==TYPE_ALL){
                    nextsong();
                }
                if(type==TYPE_ONE){
                    mediaPlayer.start();
                }
                if(type==TYPE_STOP){
                    play.setBackgroundResource(R.drawable.music_stop);
                }
            }
        });

        play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(!isnew){
                    if(mediaPlayer.isPlaying()) {
                        mediaPlayer.pause();
                        play.setBackgroundResource(R.drawable.music_stop);
                    }else{
                        mediaPlayer.start();
                        play.setBackgroundResource(R.drawable.music_play);
                    }
                }else{
                    isnew=false;
                    musicplay();
                }
            }
        });
        changetype.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(type == TYPE_STOP){
                    type=TYPE_ONE;
                    changetype.setBackgroundResource(R.drawable.music_circle1);
                    //Toast.makeText(mactivity, "单曲", Toast.LENGTH_SHORT).show();
                    typetext.setText("方式：单曲循环");
                }else if(type == TYPE_ONE){
                    type=TYPE_ALL;
                    changetype.setBackgroundResource(R.drawable.music_circleall);
                    //Toast.makeText(mactivity, "列表循环", Toast.LENGTH_SHORT).show();
                    typetext.setText("方式：列表循环");
                }else if(type == TYPE_ALL){
                    type=TYPE_STOP;
                    changetype.setBackgroundResource(R.drawable.music_notcircle);
                    //Toast.makeText(mactivity, "不循环", Toast.LENGTH_SHORT).show();
                    typetext.setText("方式：不循环");
                }
            }
        });
    }

//    @Override
//    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
//        inflater.inflate(R.menu.friend_menu, menu);
//        MenuItemCompat.setShowAsAction(menu.findItem(R.id.friend_add),MenuItemCompat.SHOW_AS_ACTION_ALWAYS);
//        super.onCreateOptionsMenu(menu, inflater);
//    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case R.id.friend_add:
                //Toast.makeText(mactivity,"添加",Toast.LENGTH_SHORT).show();
                break;
            case android.R.id.home:
                //Toast.makeText(mactivity,"侧边栏",Toast.LENGTH_SHORT).show();
                mactivity.showDrawer();
                break;
        }
        return true;
    }

    private void initRems(){


    }
    private void initMusic(){
        initFolder();
    }
    private void initMediaPlayer(){
        try{
            File file=new File(Environment.getExternalStorageDirectory(),"music.mp3");
            mediaPlayer.setDataSource(file.getPath());
            mediaPlayer.prepare();
            Toast.makeText(mactivity, "准备", Toast.LENGTH_SHORT).show();
        }catch (Exception e){
            Toast.makeText(mactivity, "失败", Toast.LENGTH_SHORT).show();
        }
    }
    private void initFolder(){
        File file=new File(Environment.getExternalStorageDirectory(),"MusicOldFriend");
        try {
            readfile(file.getPath());
        } catch (IOException e) {
            Toast.makeText(mactivity, "异常", Toast.LENGTH_SHORT).show();
        }
    }
    public boolean readfile(String filepath) throws FileNotFoundException, IOException{
        try{
            File file = new  File(filepath);
            if(!file.isDirectory()){
                file.mkdir();
                Toast.makeText(mactivity, "文件夹不存在", Toast.LENGTH_SHORT).show();
                Result msg1= new Result("周杰伦"," "," ");
                musicList.add(msg1);
            }else if(file.isDirectory()){
                String[] filelist=file.list();
                //Toast.makeText(mactivity, "文件夹存在", Toast.LENGTH_SHORT).show();
                for(int i =0;i<filelist.length;i++){
                    File readfile=new File(filepath+"//"+filelist[i]);
                    if(!readfile.isDirectory()){
                        if(readfile.exists()) {
                            String name = readfile.getName();
                            //Toast.makeText(mactivity, readfile.getPath(), Toast.LENGTH_SHORT).show();
                            if (name.endsWith("mp3")) {
                                String path=readfile.getPath();
                                Result rem1=new Result(name," ",path);
                                musicList.add(rem1);
                            }
                        }
                    }else if(readfile.isDirectory()){
                        readfile(filepath+"//"+filelist[i]);
                    }
                }
            }
        }catch(FileNotFoundException e){
            Toast.makeText(mactivity, "异常:未找到文件", Toast.LENGTH_SHORT).show();
        }
        if(musicList.size()==0){
            Toast.makeText(mactivity, "列表空", Toast.LENGTH_SHORT).show();
            Result msg1= new Result("周杰伦"," "," ");
            musicList.add(msg1);
        }
        return true;
    }


    public boolean musicplay(){
        play.setBackgroundResource(R.drawable.music_play);
        String path=musicList.get(number).getURL();
        String name=musicList.get(number).getTitle();
        songtext.setText(name);
        try {
            mediaPlayer.reset();
            mediaPlayer.setDataSource(path);
            mediaPlayer.prepare();
            mediaPlayer.start();
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public void nextsong(){
        if(number<musicList.size()-1){
            number=number+1;
            musicplay();
        }else{
            number=0;
            musicplay();
        }
    }

    public static FragmentFriend newInstance(String arg){
        FragmentFriend FragmentFriend = new FragmentFriend();
        Bundle args = new Bundle();
        args.putString("fFriend", arg);
        FragmentFriend.setArguments(args);
        return FragmentFriend;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(mediaPlayer!=null){
            mediaPlayer.stop();
            mediaPlayer.release();
        }
    }
}
